<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, toRaw } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { getAllGroupApi } from '@/apis/department'
import {
  deleteStationByStationInfoApi,
  getAllManagerApi,
  getStationsByManagerNameApi,
  getStationsLimitByManagerNameApi,
  postStationByStationInfoApi,
  putStationByStationInfoApi
} from '@/apis/station'

// const filePrefix = process.env.VUE_APP_BASE_URL
const tableLoading = ref(false)
const stationFormEditDialogVisible = ref(false)
const stationFormEditDialogTitle = ref('添加岗位')
const stationForm = reactive({
  data: {
    stationName: '',
    stationRequires: '',
    status: '',
    id: 0,
    managerName: '',
    groupId: ''
  }
})

const stations = ref([])
const method = ref('')
const managers = ref([])
const managerName = ref('')
const pageparm = ref({
  pageNum: 1,
  pageSize: 10,
  total: 10
})
const stationFormRef = ref()
const stationFormRules = ref({
  stationName: [{required: true, message: '请输入岗位名称', trigger: 'blur'}],
  status: [{required: true, message: '请输入岗位状态', trigger: 'blur'}],
  managerName: [{required: true, message: '请输入岗位负责人', trigger: 'blur'}],
  groupId: [{required: true, message: '请输入岗位所在工作组', trigger: 'blur'}]
})

const handleEdit = (index, row) => {
  getAllGroups()
  stationFormEditDialogVisible.value = true
  if (row != undefined && row != 'undefined') {
    method.value = 'update'
    stationFormEditDialogTitle.value = '修改岗位'
    stationForm.data = row
  } else {
    method.value = 'add'
    stationFormEditDialogTitle.value = '添加岗位'
    stationForm.data = {
      stationName: '',
      stationRequires: '',
      status: '',
      id: 0,
      managerName: '',
      groupId: ''
    }
  }
}

const submitStationForm = formEL => {
  formEL.validate(valid => {
    if (valid) {
      if (method.value == 'add') {
        postStationByStationInfoApi(toRaw(stationForm).data)
            .then(() => {
              getStations()
              ElMessage({type: 'success', message: '岗位新增成功！'})
              stationFormEditDialogVisible.value = false
            })
            .catch(() => {
              stationFormEditDialogVisible.value = false
              ElMessage.error('岗位新增失败，请稍后再试！')
            })
      } else {
        putStationByStationInfoApi(toRaw(stationForm).data)
            .then(() => {
              getStations()
              ElMessage({type: 'success', message: '岗位修改成功！'})
              stationFormEditDialogVisible.value = false
            })
            .catch(() => {
              ElMessage.error('岗位修改失败，请稍后再试！')
            })
      }
    }
  })
}

const deleteStation = (index, row) => {
  ElMessageBox.confirm(`确定删除 "<font color="red">${ row.stationName }</font>" 岗位？`, '信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    dangerouslyUseHTMLString: true,
    type: 'warning'
  })
      .then(() => {
        deleteStationByStationInfoApi(row)
            .then(() => {
              getStations()
              ElMessage({type: 'success', message: `${ row.stationName } 岗位已被删除！`})
            })
            .catch(() => {
              ElMessage.error('删除岗位失败，请稍后再试！')
            })
      })
      .catch(() => {
        ElMessage({type: 'info', message: '已取消删除'})
      })
}

const closeDialog = dialog => {
  if (dialog == 'edit') {
    stationFormEditDialogVisible.value = false
  }
}

const handleChangePage = (nowPageNum) => {
  pageparm.value.pageNum = nowPageNum
  getStations()
}

const getStations = () => {
  tableLoading.value = true
  getStationsLimitByManagerNameApi(managerName.value, pageparm.value.pageNum, pageparm.value.pageSize)
      .then(({data}) => {
        stations.value = data.dataList
        pageparm.value.total = data.total
      })
      .finally(() => {
        tableLoading.value = false
      })
}

const getStationsByManagerName = () => {
  getStationsByManagerNameApi(managerName.value).then(({data}) => {
    stations.value = data
    pageparm.value.total = data.length
  })
}

const fomatterStatus = (row, colume, ceilValue, index) => {
  if (row.status == 2) {
    return '紧急招聘'
  } else if (row.status == 1) {
    return '正在进行中'
  } else {
    return '停止招聘'
  }
}

const getAllManager = () => {
  getAllManagerApi().then(({data}) => {
    managers.value = data
  })
}
const groups = ref([])
const getAllGroups = () => {
  getAllGroupApi().then(({data}) => {
    groups.value = data
  })
}

onMounted(() => {
  getStations()
  getAllManager()
})
</script>

<template>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 24px">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>岗位管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-form :inline="true" class="user-search-form">
    <el-form-item label="负责人：">
      <el-select v-model="managerName" placeholder="请选择负责人" style="width: 200px">
        <el-option key="" label="全部负责人" value="%"></el-option>
        <el-option v-for="item in managers" :key="item" :label="item" :value="item" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :icon="Search" @click="getStationsByManagerName">搜索</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :icon="Plus" @click="handleEdit()">添加岗位</el-button>
    </el-form-item>
  </el-form>
  <!--列表-->
  <el-table :data="stations" highlight-current-row v-loading="tableLoading" stripe style="width: 100%" height="76%">
    <el-table-column align="center" type="selection" width="60"></el-table-column>
    <el-table-column sortable prop="stationName" label="岗位名称" width="200"></el-table-column>
    <el-table-column sortable prop="stationRequires" label="岗位描述" width="500"></el-table-column>
    <el-table-column sortable prop="publishTime" label="发布时间" width="100"></el-table-column>
    <el-table-column sortable :formatter="fomatterStatus" label="岗位状态" width="100"></el-table-column>
    <el-table-column prop="managerName" label="负责人" width="160">
      <!--      <template #default="scope">-->
      <!--        <avatar-name :url="scope.row.owner.avatar ? filePrefix + scope.row.owner.avatar : scope.row.owner.name"-->
      <!--                     :name="scope.row.owner.name"/>-->
      <!--      </template>-->
    </el-table-column>
    <el-table-column align="center" label="操作" min-width="200" fixed="right">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button type="danger" @click="deleteStation(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination background layout="prev, pager, next" :total="pageparm.total" :page-size="10"
                 @current-change="handleChangePage" />
  <el-dialog :title="stationFormEditDialogTitle" v-model="stationFormEditDialogVisible" width="30%">
    <el-form label-width="120px" :model="stationForm.data" ref="stationFormRef" :rules="stationFormRules">
      <el-form-item label="岗位名称" prop="stationName">
        <el-input v-model="stationForm.data.stationName" auto-complete="off" placeholder="请输入岗位名称"></el-input>
      </el-form-item>
      <el-form-item label="岗位描述" prop="stationRequires">
        <el-input
            v-model="stationForm.data.stationRequires"
            auto-complete="off"
            placeholder="请输入岗位描述"
        ></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="managerName">
        <el-input v-model="stationForm.data.managerName" auto-complete="off" placeholder="请输入负责人姓名"></el-input>
      </el-form-item>
      <el-form-item label="岗位状态" prop="status">
        <el-select v-model="stationForm.data.status" placeholder="请输入岗位状态">
          <el-option label="紧急招聘" :value="2"></el-option>
          <el-option label="正在进行中" :value="1"></el-option>
          <el-option label="停止招聘" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作组" prop="groupId">
        <el-select v-model="stationForm.data.groupId" placeholder="请输入工作组">
          <el-option v-for="item in groups" :key="item.id" :label="item.gName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog('edit')">取消</el-button>
      <el-button type="primary" :loading="tableLoading" class="title" @click="submitStationForm(stationFormRef)"
      >保存
      </el-button
      >
    </div>
  </el-dialog>
</template>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}

:deep(.el-table__inner-wrapper) {
  height: 100% !important;
}
</style>
